package com.thinkcube.edutainment.fragment;

import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.thinkcube.edutainment.BuyLessonActivity;
import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.Util;
import com.thinkcube.edutainment.adapters.MobileNumberAdapter;
import com.thinkcube.edutainment.client.CourseClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.Purchase;
import com.thinkcube.edutainment.domain.data.CourseData;
import com.thinkcube.edutainment.domain.data.LessonData;
import com.thinkcube.edutainment.domain.data.MobileNumber;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;
import com.thinkcube.edutainment.domain.dto.PaymentDto;
import com.thinkcube.edutainment.service.SPreferences_;

@EFragment(R.layout.payment_confrimation)
public class PaymentConfrimationFragment extends Fragment implements
		OnCheckedChangeListener {

	@ViewById(R.id.charging_no)
	Spinner chargingNo;

	@ViewById(R.id.pay_btn)
	Button payButton;

	@ViewById(R.id.payment_method_rb)
	RadioGroup paymentMethodRb;

	@ViewById(R.id.charging_no_lb)
	TextView mobileNoTitle;

	@ViewById(R.id.instalments)
	TextView insatalment;

	@ViewById(R.id.payment_plan)
	TextView paymentPlan;

	@ViewById(R.id.payment_mode)
	TextView paymentMode;

	@ViewById(R.id.daily_instalment)
	TextView price;

	@ViewById(R.id.progressBar)
	ProgressBar progress;
	
	@ViewById(R.id.progressBar_spiner)
	ProgressBar progressSpinner;
	
	@ViewById(R.id.daily_instalment_lb)
	TextView instalmentLb;
	
	@ViewById(R.id.back_btn)
	Button back;
	
	@ViewById(R.id.eazy_cach)
	RadioButton eazyCash;
	
	@ViewById(R.id.credit_card)
	RadioButton creditCard;
	
	@ViewById(R.id.mobile_cash)
	RadioButton mobileCash;
	

	CourseData courseData;

	LessonData lessonData;

	PaymentDto paymentDto;

	String paymentModeValue;
	String pPlanValue;
	String noOfInstallment;
	String priceValue;
	String itemType;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments().containsKey("paymentDto")) {
			paymentDto = getArguments().getParcelable("paymentDto");

		}

		if (getArguments().containsKey("courseObject")) {

			courseData = getArguments().getParcelable("courseObject");
		}

		if (getArguments().containsKey("mode")) {
			paymentModeValue = getArguments().getString("mode");
			System.out.println("####  paymentModeValue "+paymentModeValue);
		}

		if (getArguments().containsKey("plan")) {
			pPlanValue = getArguments().getString("plan");
			System.out.println("####  pPlanValue "+pPlanValue);
		}

		if (getArguments().containsKey("#installment")) {
			noOfInstallment = getArguments().getString("#installment");
			System.out.println("####  Instalment "+noOfInstallment);
		}

		if (getArguments().containsKey("price")) {
			priceValue = getArguments().getString("price");
		}

		if (getArguments().containsKey("type")) {
			itemType = getArguments().getString("type");
		}

		if (getArguments().containsKey("lessonObject")) {
			lessonData = getArguments().getParcelable("lessonObject");
		}

	}

	@AfterViews
	void initUi() {
		gettokenforUser();
		paymentMethodRb.setOnCheckedChangeListener(this);
		setSummeryData();
		if(itemType.equals("lesson"))
		{
			back.setText("Cancel");
		}
		
		System.out.println("SUBCRIPTION PLAN    "+courseData.getSubscription_plan());
		
		if(((courseData.getSubscription_plan().equals("1"))&&(paymentModeValue.equals(EdutainmentConstant.PAYMENT_MODE_INSTALLMENT)))
				||(courseData.getSubscription_plan().equals("2"))&&(paymentModeValue.equals(EdutainmentConstant.PAYMENT_MODE_INSTALLMENTS)))
		{
			
			
			if((pPlanValue.equals(EdutainmentConstant.PAYMENT_PLAN_DAILY))||((pPlanValue.equals(EdutainmentConstant.PAYMENT_PLAN_WEEKLY))))
			{
			  
			   eazyCash.setVisibility(View.INVISIBLE);
			   creditCard.setVisibility(View.INVISIBLE);
			   mobileCash.setChecked(true);
			
			}
		}
	}

	@AfterViews
	@Background
	void gettokenforUser() {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					getUser(userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});

	}

	void getUser(OAuth requestToken) {

		courseDto.setAuthToken(requestToken.getoAuth().getToken());
		courseDto.setUserId(pref.getId().get());

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					addMobilNoToSpinner(userClient
							.getUserProfileInformation(
									courseDto.getMultiValuedMap()).getUser()
							.getMobileNumbers());
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});
	}

	@Bean
	MobileNumberAdapter mobileNumberAdapter;

	@UiThread
	void addMobilNoToSpinner(List<MobileNumber> list) {
		// ArrayList<String> nos = new ArrayList<String>();
		// for (MobileNumber mobileNumbers : list) {
		// nos.add(mobileNumbers.getNumber());
		// }
		//
		// mobileNumbersList = list;
		//
		// ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
		// getActivity(), R.layout.my_spinner_item, nos);
		// dataAdapter.setDropDownViewResource(R.layout.my_spinner_drop_down_item);

		for (MobileNumber mobileNumber : list) {
			System.out.println("mobile number" + mobileNumber.getNumber());
		}

		mobileNumberAdapter.setMobileNumber(list);
		
		chargingNo.setAdapter(mobileNumberAdapter);
		
		progressSpinner.setVisibility(View.GONE);
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {

		switch (checkedId) {
		case R.id.mobile_cash:
			
			clickMobileCache();
			
			break;

		case R.id.eazy_cach:
			
			clickEazyCache();
			
			break;

		case R.id.credit_card:
			
			clikCreditCard();
			
			break;

		default:
			break;
		}

	}

	@Bean
	OAuthDto oAuthDto;

	@RestService
	UserClient userClient;

	@RestService
	CourseClient courseClient;

	@Trace
	// @AfterViews
	@Background
	void gettoken(final PaymentDto paymentDto2) {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					payment(paymentDto2, userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});
	}

	@Pref
	SPreferences_ pref;

	@Background
	void payment(PaymentDto paymentDto2, OAuth requestToken) {

		paymentDto.setAuthToken(requestToken.getoAuth().getToken());
		paymentDto.setUserId(pref.getId().get());

		paymentDto.setItemType(itemType);

		if (courseData != null) {
			paymentDto.setItemId(courseData.getCourseId());
		}

		if (lessonData != null) {
			paymentDto.setItemId(lessonData.getLessonId());
		}

		if(paymentDto.getPaymentMethod()!=null){
			
			showProgress();
			System.out.println("Payment parameters ::::");
			System.out.println("coupon code ::::" + paymentDto.getCouponCode());
			System.out.println("coupon id ::::" + paymentDto.getCouponId());
			System.out.println("item id ::::" + paymentDto.getItemId());
			System.out.println("item type ::::" + paymentDto.getItemType());
			System.out.println("mobilr number ::::"
					+ paymentDto.getMobileNumberId());
			System.out.println("Payment plan ::::" + paymentDto.getPaymentPlan());
			System.out.println("user id ::::" + paymentDto.getUserId());
			System.out.println("payment method ::::"
					+ paymentDto.getPaymentMethod());
	
			new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {
	
				@Override
				public void onReachabilityTestPassed() {
	
					try {
	
						doUiPurchase(courseClient.purchase(paymentDto
								.getMultiValuedMap()));
	
					} catch (Exception e) {
	
						System.err.println(e);
					}
				}
	
				@Override
				public void onReachabilityTestFailed() {
	
					showMessge("Not connected ");
				}
			});
		
		}else
		{
			showMessge("Please select a payment method. ");
		}

	}
	
	@UiThread
	void showProgress()
	{
		progress.setVisibility(View.VISIBLE);
	}

	@Trace
	@UiThread
	void doUiPurchase(final Purchase purchase) {
		
		final Activity activity=getActivity();
		
		System.out.println("ACTIVITY >>>"+activity);
		progress.setVisibility(View.GONE);
		//System.out.println("purchase " + purchase.getMessageText());
		/* map this purchase string into object */
		if (purchase.getData() != null) {

			FragmentTransaction fragmentTransaction = getFragmentManager()
					.beginTransaction();

			Bundle bundle = new Bundle();

			bundle.putString("content", purchase.getData());
			HtmlFragment htmlLessons = new HtmlFragment_();
			htmlLessons.setArguments(bundle);

			fragmentTransaction.replace(R.id.payment_details, htmlLessons);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();

		} else {
			final Dialog dialog = new Dialog(getActivity());
			dialog.setContentView(R.layout.payment_dialog);
			// dialog.setTitle("Title...");

			// set the custom dialog components - text, image and button
			TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
			text.setText(purchase.getMessageText());

			System.out.println("PAYMENT STATUS " + purchase.getStatus());

			Button dialogButton = (Button) dialog.findViewById(R.id.dialog_ok);
			// if button is clicked, close the custom dialog
			dialogButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					purchase.getStatus();

					if (purchase.getStatus().equals("true")) {
						
						
						activity.setResult(1);
						activity.getIntent().putExtra("MSG", "SUCCESS");
						activity.finish();
						
					} else {

					}

					dialog.dismiss();
					

				}
			});

			dialog.show();
		}

	}

	@UiThread
	void showMessge(final String msg) {

		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	@Bean
	CourseDto courseDto;

	@Click(R.id.back_btn)
	void backBtnClick() {

		getFragmentManager().popBackStack();
		
		if(itemType.equals("lesson"))
		{
			getActivity().finish();
		}

	}

	@Click(R.id.pay_btn)
	void doPayment() {
		//progress.setVisibility(View.VISIBLE);

		if (paymentDto.getPaymentMethod() != null) {
			if (paymentDto.getPaymentMethod().equals("1")) {
				if (chargingNo.getSelectedItem() != null) {

					MobileNumber mobileNumber = (MobileNumber) chargingNo
							.getSelectedItem();

					System.out.println("mobile " + mobileNumber.getNumber());

					// String mobile = chargingNo.getSelectedItem().toString();
					//
					// paymentDto.setMobileNumberId(mobile);
					// System.out.println("mobile" + mobile);
					paymentDto.setMobileNumberId(mobileNumber.getId());
					//paymentDto.setMobileNumberId("124235345634");
				}
				//

			} else {

			}

		}

		gettoken(paymentDto);

	}

	void clickMobileCache() {
		
		if(progressSpinner.getVisibility()==View.INVISIBLE)
		{
			progressSpinner.setVisibility(View.VISIBLE);
		}

		if (chargingNo.getVisibility() == View.INVISIBLE) {
			
			chargingNo.setVisibility(View.VISIBLE);
			mobileNoTitle.setVisibility(View.VISIBLE);
		}
		paymentDto.setPaymentMethod("1");
	}

	void clickEazyCache() {

		chargingNo.setVisibility(View.INVISIBLE);
		mobileNoTitle.setVisibility(View.INVISIBLE);
		paymentDto.setPaymentMethod("3");
	}

	void clikCreditCard() {

		chargingNo.setVisibility(View.INVISIBLE);
		mobileNoTitle.setVisibility(View.INVISIBLE);
		paymentDto.setPaymentMethod("2");
	}

	void setSummeryData() {

		/*
		 * if(noOfInstallment!=null) {
		 * 
		 * } if(pPlanValue!=null) {
		 * 
		 * }
		 */

		paymentPlan.setText(pPlanValue);
		insatalment.setText(noOfInstallment);
		paymentMode.setText(paymentModeValue);
		price.setText(priceValue);
		
		if((itemType.equals("lesson"))||(paymentModeValue.equals(EdutainmentConstant.PAYMENT_MODE_FULLPAYMENT)))
		{
			instalmentLb.setText("Total");
			
		}else
		{
			instalmentLb.setText(pPlanValue+" "+"Installments");
		}
		

	}
}
